﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp26
{
    public class DragInCanvasBehavior : Behavior<UIElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
            this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
            this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
        }

        private bool isDrawging = false;
        private Point ePoint = new();
        private Point mPoint = new();
        private Canvas? canvas;

        private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ePoint.X = Canvas.GetLeft(AssociatedObject);
            ePoint.Y = Canvas.GetTop(AssociatedObject);

            if (canvas == null)
            {
                canvas = (Canvas)LogicalTreeHelper.GetParent(AssociatedObject);
            }
            mPoint = e.GetPosition(canvas);

            AssociatedObject.CaptureMouse();//捕获鼠标
            isDrawging = true;  
        }
        private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isDrawging)
            {
                Point point = e.GetPosition(canvas);

                AssociatedObject.SetValue(Canvas.LeftProperty, ePoint.X + (point.X - mPoint.X));
                AssociatedObject.SetValue(Canvas.TopProperty, ePoint.Y + (point.Y - mPoint.Y));
            }
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (isDrawging)
            {
                AssociatedObject.ReleaseMouseCapture();

                isDrawging = false;
            }
         
        }



    

   
    }
}
